#include "graphsupport/solve/facilitylocation/ChooseCheapestFacilityHeuristic.h"

#include "accumulsupport/AccumulSupport.h"

bool ChooseCheapestFacilityHeuristic::solve(
	FacilitiesGraph & fgraph,
	std::vector< char > & isFacilityOpenVec,
	std::vector< int > & cityWitnessVec
)
{
	int citiesCount = fgraph.getCitiesCount();
	int facilitiesCount = fgraph.getFacilitiesCount();

	if ( isFacilityOpenVec.size() != facilitiesCount )
	{
		accumf::reinit( isFacilityOpenVec, fgraph.getFacilitiesCount(), true );
	}
	accumf::reinit( cityWitnessVec, fgraph.getCitiesCount(), -1 );

	for ( int city = 0; city < citiesCount; city++ )
	{
		int witness = -1;
		FacilitiesGraph::FacilityPriceType cheapest = fgraph.getInfEdge();
		for ( int facility = 0; facility < facilitiesCount; facility++ )
		{
			if ( cheapest > fgraph.getFSEdge( city, facility ) && isFacilityOpenVec[facility] )
			{
				cheapest = fgraph.getFSEdge( city, facility );
				witness = facility;
			}
		}
		if ( witness == -1 )
		{
			return false;
		}
		cityWitnessVec[city] = witness;
	}

	return true;
}
